#include "widget_funca_smart_chat.h"
#include "ui_widget_funca_smart_chat.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDateTime>
#include <QScrollBar>
#include <QTimer>
#include <QPixmap>

Widget_funcA_Smart_chat::Widget_funcA_Smart_chat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcA_Smart_chat)
{
    ui->setupUi(this);

    // 初始化消息容器
    messagesContainer = new QWidget(ui->scrollArea);
    messagesLayout = new QVBoxLayout(messagesContainer);
    messagesLayout->setAlignment(Qt::AlignTop);
    messagesLayout->setSpacing(10);
    messagesLayout->setContentsMargins(10, 10, 10, 10);
    
    ui->scrollArea->setWidget(messagesContainer);
    ui->scrollArea->setWidgetResizable(true);

    // 设置输入框
    ui->textEdit->setPlaceholderText("请输入...");
    
    // 初始化AI
    deepseek = new Deepseek_Chat(this);

    connect(deepseek, &Deepseek_Chat::replyReady, this, [&](const QString &reply) {
        addMessage("Deepseek", reply, false);
    });

    connect(deepseek, &Deepseek_Chat::error_signals, this, [&](const QString &error) {
        addMessage("Deepseek", "错误: " + error, false);
    });
}

Widget_funcA_Smart_chat::~Widget_funcA_Smart_chat()
{
    delete ui;
}

void Widget_funcA_Smart_chat::addMessage(const QString &sender, const QString &message, bool isUser)
{
    // 创建消息容器
    QWidget *messageWidget = new QWidget(messagesContainer);
    QHBoxLayout *messageLayout = new QHBoxLayout(messageWidget);
    messageLayout->setContentsMargins(0, 0, 0, 0);
    messageLayout->setSpacing(10);

    // 头像
    QLabel *avatarLabel = new QLabel(messageWidget);
    QPixmap avatar(isUser ? ":/new/prefix1/头像" : ":/new/prefix1/Deepseek");
    avatarLabel->setPixmap(avatar.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    avatarLabel->setFixedSize(40, 40);
    avatarLabel->setStyleSheet("border-radius: 20px;");

    // 消息内容
    QWidget *contentWidget = new QWidget(messageWidget);
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
    contentLayout->setContentsMargins(0, 0, 0, 0);
    contentLayout->setSpacing(2);

    // 昵称
    QLabel *nameLabel = new QLabel(sender, contentWidget);
    nameLabel->setStyleSheet("font-weight: bold; color: #666; font-size: 12px;");

    // 消息气泡
    QLabel *textLabel = new QLabel(message, contentWidget);
    textLabel->setWordWrap(true);
    textLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
    textLabel->setStyleSheet(QString("background: %1; border-radius: 8px; padding: 8px; max-width: %2px;")
                         .arg(isUser ? "#e3f2fd" : "#f5f5f5")
                         .arg(ui->scrollArea->width() * 0.7));
    textLabel->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);

    // 时间
    QLabel *timeLabel = new QLabel(QDateTime::currentDateTime().toString("hh:mm"), contentWidget);
    timeLabel->setStyleSheet("color: #999; font-size: 10px;");

    contentLayout->addWidget(nameLabel);
    contentLayout->addWidget(textLabel);
    contentLayout->addWidget(timeLabel);

    // 布局方向
    if (isUser) {
        messageLayout->addStretch();
        messageLayout->addWidget(contentWidget);
        messageLayout->addWidget(avatarLabel);
    } else {
        messageLayout->addWidget(avatarLabel);
        messageLayout->addWidget(contentWidget);
        messageLayout->addStretch();
    }

    messagesLayout->addWidget(messageWidget);

    // 滚动到底部
    QTimer::singleShot(0, this, [this]() {
        ui->scrollArea->verticalScrollBar()->setValue(ui->scrollArea->verticalScrollBar()->maximum());
    });
}

void Widget_funcA_Smart_chat::on_pushButton_clicked()
{
    QString text = ui->textEdit->toPlainText().trimmed();
    if (text.isEmpty()) return;
    addMessage("1196kk", text, true);
    deepseek->ask(text);
    ui->textEdit->clear();
}

void Widget_funcA_Smart_chat::onTextChanged()
{
    ui->pushButton->setEnabled(!ui->textEdit->toPlainText().trimmed().isEmpty());
}

void Widget_funcA_Smart_chat::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    
    // 调整消息气泡宽度
    for (int i = 0; i < messagesLayout->count(); ++i) {
        if (auto messageWidget = qobject_cast<QWidget*>(messagesLayout->itemAt(i)->widget())) {
            if (auto textLabel = messageWidget->findChild<QLabel*>()) {
                textLabel->setStyleSheet(textLabel->styleSheet().replace(
                    QRegExp("max-width: \\d+px"), 
                    QString("max-width: %1px").arg(ui->scrollArea->width() * 0.7)
                ));
            }
        }
    }
}
